package mutiyi.manager;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;
/**
 * Author:yang
 * Date:2024-03-06 8:57
 * 配置管理器
 */
public class ConfigManager {

  private Properties configData;

  public ConfigManager() {
    this.configData = new Properties();
  }

  // 加载路径下的配置文件
  public void loadConfig(String configFilePath) {
    try (FileReader reader = new FileReader(configFilePath)) {
      configData.load(reader);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  // 更新文件信息
  public void updateConfig(String key, String value) {
    configData.setProperty(key, value);
  }

  // 获取对应key的value
  public String getConfigValue(String key) {
    return configData.getProperty(key);
  }

  // 创建对象
  public <T> T createObjectFromConfig(Class<T> clazz) throws IllegalAccessException, InstantiationException {
    T instance = clazz.newInstance();

    // 获取类的所有属性
    Field[] fields = clazz.getDeclaredFields();

    // 遍历配置信息，将配置值注入到对象中
    for (String key : configData.stringPropertyNames()) {
      for (Field field : fields) {
        if (field.getName().equals(key)) {
          field.setAccessible(true);
          try {
            // 根据属性类型进行类型转换
            if (field.getType() == int.class) {
              field.setInt(instance, Integer.parseInt(configData.getProperty(key)));
            } else if (field.getType() == boolean.class) {
              field.setBoolean(instance, Boolean.parseBoolean(configData.getProperty(key)));
            } else {
              field.set(instance, configData.getProperty(key));
            }
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
          break;
        }
      }
    }

    return instance;
  }

  // 存储文件
  public void saveConfigToFile(String filePath) {
    try (FileWriter writer = new FileWriter(filePath)) {
      configData.store(writer, "Configuration File");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
